package com.db.chat.client;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * Simple tool to input from a separate window to chat.
 */
public class ClientConsoleInput {
    private static final int DEFAULT_PORT = 9999;

    public static void main(String[] args) {
        int port;
        if (args.length > 0) {
            port = Integer.valueOf(args[0]);
        } else {
            port = DEFAULT_PORT;
        }
        System.out.println("WRITE HERE! (used port "+port +")");
        try (Socket socket = new Socket("localhost", port);
             BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
             BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));) {

            String command = null;
            while (!("/exit".equals(command))) {
                command = br.readLine();
                bw.write(command);
                bw.newLine();
                bw.flush();
            }
        } catch (UnknownHostException e) {
            System.out.println("System does not support localhost value "+e);
        } catch (IOException e) {
            System.out.println("IO Failure, aborting "+e);
        } catch (NullPointerException e) {
            System.out.println("Hard abort "+e);
        }
    }
}
